import router from './router'
import axios from 'axios'
import store from './store'
import { ElMessage } from "element-plus";
const url = {
    load: 'https://images.weserv.nl/?url=',
    server: 'http://localhost:9090/',
}


// request请求拦截器
axios.interceptors.request.use((config) => {
    console.log("1-==========================")
    //如果存在token，请求携带token
    if (localStorage.getItem('userInfo')) {
        console.log("w-==========================")
        // 给所有请求添加请求头Authorization存放token，这部分和后端过滤器对应 （'Bearer '对应后端令牌前缀）
        config.headers['Authorization'] = 'Bearer ' + JSON.parse(localStorage.getItem('userInfo')).token
    }
    return config ;
}, (error) => {
    console.log("拦截请求失败",error)
})
// http response 拦截器
axios.interceptors.response.use(
    response => {
        // 从pendingRequest对象中移除请求
        return response;
    },
    error => {
        // 从pendingRequest对象中移除请求
        if (error.response) {
            console.log("error.response=======" + error.response.status)
            switch (error.response.status) {
                case 401:
                    console.log("401=============================")
                    // 返回 401 清除token信息并跳转到登录页面
                    ElMessage.error("请先登录！");
                    store.commit('changeLogView')
                    break
                case 402:
                //无此视频
                    router.push({name:"videoNotFound"})
                    break
                default:
                    ElMessage.error("网络异常");
            }
        }

        return Promise.reject(error)   // 返回接口返回的错误信息
    });

// --------跳转------------
//投稿请求
function goBlank(id) {
    const url = '/blank/' + id
    const routeData = router.resolve({ path: url })
    window.open(routeData.href, '_blank')
}

function goDetail(id) {
    const url = '/detail/' + id
    const routeData = router.resolve({ path: url })
    window.open(routeData.href, '_blank')
}
// 跳转入个人主页
function goPersonalHome(id) {
    const url = '/mainPage/' + id
    const routeData = router.resolve({ path: url })
    window.open(routeData.href, '_blank')
}

function goUser(id) {
    const url = '/user/' + id
    const routeData = router.resolve({ path: url })
    window.open(routeData.href, '_blank')
}

const apiAxios = async (method, urls, params) => {
    //项目既定fapp
    let headers = { 'Content-Type': 'application/json' }
    //读取存储在localStorage中的token
/*    if (localStorage.getItem('userInfo')) {
        headers.token = JSON.parse(localStorage.getItem('userInfo')).token
    }*/
    return await new Promise((resolve => {
        axios({
            //如果缓存里有token则所有请求都包含其
            headers: headers,
            method: method,
            url: url.server + urls,// 拼接url（后端接口）
            //数据内容
            data: method === 'POST' ? params : null,
            params: method === 'GET' ? params : null
        }).then((res) => {
            // console.log(res.data)
            resolve(res.data)
        }).catch(e => {
            console.log("发送"+urls+"请求出错",e)
        })
    }))
}
const apiAxiosByUpload = async (method, urls, params) => {
    let headers = { 'Content-Type': 'multipart/form-data' }
    return await new Promise((resolve => {
        axios({
            //如果缓存里有token则所有请求都包含其
            headers: headers,
            method: method,
            url: url.server + urls,// 拼接url（后端接口）
            //数据内容
            data: method === 'POST' ? params : null,
            params: method === 'GET' ? params : null
        }).then((res) => {
            // console.log(res.data)
            resolve(res.data)
        }).catch(e => {
            console.log("发送"+urls+"请求出错",e)
        })
    }))
}

//get请求
const get = async (url, params) => {
    return await apiAxios('GET', url, params)
}
//post请求
const post = async (url, params) => {
    return await apiAxios('POST', url, params)
}

const uploadPicture = async (url,params) => {
    return await apiAxiosByUpload('POST',url,params)
}


function numChange(num) {
    if (num >= 10000) {
        var n1 = Math.floor(num / 10000)
        var n2 = Math.floor((num % 10000) / 1000)
        if (n2 == 0) {
            return n1 + '万'
        } else {
            return n1 + '.' + n2 + '万'
        }
    } else {
        return num
    }
}

export default {
    url,
    goBlank,
    goDetail,
    goPersonalHome,
    goUser,
    get,
    post,
    numChange,
    uploadPicture
}
